import React, {Component, PropTypes} from 'react';
import classNames from 'classnames';
import $ from 'jquery';

/**
 * 评分组件
 */
export default class Rate extends Component{

	static defaultProps = {
		onChange: null,
		count: 5,
		defValue: 0,
		allowHalf: false, //是否允许半角
		disabled: false  //是否可用
	}

	static propTypes = {
		onChange: PropTypes.func,
		count: PropTypes.number,
		defValue: PropTypes.number,
		allowHalf: PropTypes.bool,
		disabled: PropTypes.bool
	}

	constructor(props){
		super(props);
		let {
			defValue: value,
		} = this.props;
		this.state = {value, hoverValue: undefined};
	}

	getValue = () => this.state.value;

	onClick = (e) =>{
		let {disabled, onChange} = this.props;
		if(!disabled){
			let index = this.getStarIndex(e.target);
			let value = this.getStarValue(index, e.target.pageX);
			if(value != this.state.value){
				this.setState({value});
				if(onChange){
					onChange(value);
				}
			}
		}
	}

	onHover = (e) => {
		let {disabled} = this.props;
		if(!disabled){
			let index = this.getStarIndex(e.target);
			let value = this.getStarValue(index, e.pageX);
			this.setState({hoverValue: value});
		}
	}

	onMouseLeave = (e) =>{
		this.setState({
			hoverValue: undefined
		});
	}

	getStarIndex(star){
		if(!star) return 1;
		var $star = $(star);
		if(!$star.attr('data-index')){
			$star = $star.parent();
		}
		let index = $star.attr('data-index');
		return parseInt(index);
	}

	getStarValue(index, x){
		let value = index;
		if(this.props.allowHalf){
			let target = $(this.refs['star_1']);
			let left = target.offset().left;
			if(this.props.count == 1){
				let width = target.width();
				if(left < 0) left = 0;
				if(x - left < width / 2){
					value -= 0.5;
				}
			}else{
				let width = $(this.refs['star_2']).offset().left - left;
				if(x - left - width * (index - 1) < width / 2){
					value -= 0.5;
				}
			}
		}
		return value;
	}

	render(){
		let {value , hoverValue} = this.state;
		let {count, allowHalf, disabled} = this.props;
		value = hoverValue ? hoverValue : value;

		let rateCls = classNames('rd-rate', {
			'rd-rate-disabled': disabled
		});

		let starCls = {
			'rd-rate-star': true,
			'rd-rate-star-full': !allowHalf,
			'rd-rate-star-half': allowHalf
		};

		let stars = [];
		for(let i = 1; i <= count; i++){
			let starCls = classNames({
				'rd-rate-star': true,
				'rd-rate-star-zero': i - 0.5 > value,
				'rd-rate-star-full': i <= value,
				'rd-rate-star-half': allowHalf ?  i - 0.5 <= value: false
			});
			stars.push(
				<li key={i}
					ref={`star_${i}`}
					data-index={i} 
					className={starCls} 
					onClick={disabled ? null : this.onClick}
					onMouseMove={disabled ? null : this.onHover}>
					<div className='rd-rate-star-content'/>
				</li>
			);
		}

		return (
			<ul className={rateCls} 
				onMouseLeave={disabled ? null : this.onMouseLeave}>
				{stars}
			</ul>
		);
	}
}